package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    @Override
    @Transactional
    public void try2Follow(Long followUserId, Boolean isFollow) {
        // 1. 获取当前的用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            throw new RuntimeException("请先登录");
        }
        Long userId = user.getId();
        // 2. 如果是关注则去数据库中加一条数据，在redis中加一条数据
        if (isFollow) {
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                stringRedisTemplate.opsForSet().add(RedisConstants.FOLLOW_KEY + userId, followUserId.toString());
            }
        } else {
            // 3. 如果是取关则去数据中删一条数据，去redis中删一条数据
            boolean isSuccess = remove(new LambdaUpdateWrapper<Follow>()
                    .eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId));
            if (isSuccess) {
                stringRedisTemplate.opsForSet().remove(RedisConstants.FOLLOW_KEY + userId, followUserId.toString());
            }
        }
    }

    @Override
    public boolean queryIsFollow(Long followUserId) {
        // 1. 获取当前的用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            throw new RuntimeException("请先登录");
        }
        Long userId = user.getId();
        // 2. 判断redis中有没有这个用户
        return BooleanUtil.isTrue(
                stringRedisTemplate.opsForSet()
                        .isMember(RedisConstants.FOLLOW_KEY + userId, followUserId.toString()));
    }

    @Override
    public List<UserDTO> queryCommonFollows(Long followUserId) {
        // 1. 获取当前用户的id
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            throw new RuntimeException("请先登录");
        }
        Long userId = user.getId();
        // 2. 去redis中去这两个用户的关注的交集
        String userKey = RedisConstants.FOLLOW_KEY + userId;
        String followUserKey = RedisConstants.FOLLOW_KEY + followUserId;
        Set<String> commonFollowsSet = stringRedisTemplate.opsForSet().intersect(userKey, followUserKey);
        if (CollectionUtils.isEmpty(commonFollowsSet)) {
            return Collections.emptyList();
        }
        List<Long> ids = commonFollowsSet.stream().map(Long::valueOf).collect(Collectors.toList());
        // 3. 根据ids查询数据库
        // 4. User --> UserDTO
        List<UserDTO> userDTOS = userService.listByIds(ids).stream()
                .map(dbUser -> BeanUtil.copyProperties(dbUser, UserDTO.class)).collect(Collectors.toList());
        return userDTOS;
    }
}
